//
//  ZYJSONRequestSerializer.m
//  ZYWebImage
//
//  Created by wangzhipan on 2025/4/2.
//

#import "ZYJSONRequestSerializer.h"

@implementation ZYJSONRequestSerializer
+ (instancetype)serializer
{
    return [self serializerWithWritingOptions:0];
}

+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
{
    ZYJSONRequestSerializer *jsonSerializer = [[self alloc] init];
    jsonSerializer.writingOptions = writingOptions;
    return jsonSerializer;
}

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request 
                                       params:(NSDictionary *)params
                                        error:(NSError *__autoreleasing *)error
{
    NSString *HTTPMethod = [request.HTTPMethod uppercaseString];
    if ([HTTPMethod isEqualToString:@"GET"] || [HTTPMethod isEqualToString:@"HEAD"]) {
        return [super requestBySerializingRequest:request params:params error:error];
    }
    
    NSMutableURLRequest *mutableRequest = [request mutableCopy];

    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
        if (![request valueForHTTPHeaderField:field]) {
            [mutableRequest setValue:value forHTTPHeaderField:field];
        }
    }];
    
    if (params) {
        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
            [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        }
        if (![NSJSONSerialization isValidJSONObject:params]) {
            if (error) {
                NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"ZYNetworking", nil)};
                *error = [[NSError alloc] initWithDomain:@"The `params` argument is not valid JSON." code:-1 userInfo:userInfo];
            }
            return nil;
        }
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:self.writingOptions error:error];
        if (!jsonData) {
            return nil;
        }
        mutableRequest.HTTPBody = jsonData;
    }
    return mutableRequest;
}
@end
